import os
import csv
from xml.etree.ElementTree import parse

###################################
##### defining class "parser" #####
###################################

class writer:

    def __init__(self, x):
        self.appnumber = str(x[:-4])
        self.year = self.appnumber[2:6]
        self.xmldir = 'D:\\KIPRIS\\Biblio\\'+str(self.year) + '\\' + str(self.appnumber) + ".xml"
        try :
            tree = parse(self.xmldir)
            self.parse_error = 0
        except :
            self.parse_error = 1
        if self.parse_error ==0:
            tree = parse(self.xmldir)
            self.note = tree.getroot()
            self.successYN = self.note.find("header").find("successYN").text
            if self.successYN != 'N':
                self.normal = self.note.find("body").find("item").find("biblioSummaryInfoArray").find("biblioSummaryInfo")
            else :
                self.normal = None
        else :
            self.normal = None
    
    def basicinfo(self):
        if self.normal == None:
            pass
        else :
            if self.note.find("body").find("item").find("biblioSummaryInfoArray").find("biblioSummaryInfo").find("applicationDate") != None:
                appdate = self.note.find("body").find("item").find("biblioSummaryInfoArray").find("biblioSummaryInfo").find("applicationDate").text 
            else :
                appdate =''
            if self.note.find("body").find("item").find("biblioSummaryInfoArray").find("biblioSummaryInfo").find("finalDisposal") != None:
                finaldisposal = self.note.find("body").find("item").find("biblioSummaryInfoArray").find("biblioSummaryInfo").find("finalDisposal").text
            else:
                finaldisposal = ''
            if self.note.find("body").find("item").find("biblioSummaryInfoArray").find("biblioSummaryInfo").find("registerNumber") != None:
                registernum = self.note.find("body").find("item").find("biblioSummaryInfoArray").find("biblioSummaryInfo").find("registerNumber").text
            else :
                registernum = ''
            if self.note.find("body").find("item").find("biblioSummaryInfoArray").find("biblioSummaryInfo").find("registerDate") != None:
                registerdate = self.note.find("body").find("item").find("biblioSummaryInfoArray").find("biblioSummaryInfo").find("registerDate").text
            else :
                registerdate = ''
            if self.note.find("body").find("item").find("biblioSummaryInfoArray").find("biblioSummaryInfo").find("originalExaminationRequestFlag") != None:
                exmrequst = self.note.find("body").find("item").find("biblioSummaryInfoArray").find("biblioSummaryInfo").find("originalExaminationRequestFlag").text
            else :
                exmrequst = ''
            if self.note.find("body").find("item").find("biblioSummaryInfoArray").find("biblioSummaryInfo").find("claimCount") != None:
                nclaim = self.note.find("body").find("item").find("biblioSummaryInfoArray").find("biblioSummaryInfo").find("claimCount").text
            else :
                nclaim=''
            row = [str(self.appnumber), str(appdate), str(finaldisposal), str(registernum), str(registerdate), str(exmrequst), str(nclaim)]
            wrbasicinfo.writerow(row)

    def inventor(self):
        if self.normal == None:
            pass
        else :
            try:
                inventorlist = self.note.find("body").find("item").find("inventorInfoArray").findall("inventorInfo")
                for i in range(len(inventorlist)):
                    order = i+1
                    if inventorlist[i].find("name") != None:
                        korname = inventorlist[i].find("name").text
                    else :
                        korname=''
                    if inventorlist[i].find("engName")!= None:
                        engname = inventorlist[i].find("engName").text
                    else:
                        engname=''
                    if inventorlist[i].find("code")!= None:
                        code = inventorlist[i].find("code").text
                    else :
                        code =''
                    if inventorlist[i].find("country") !=None:
                        country = inventorlist[i].find("country").text
                    else:
                        country=''
                    if inventorlist[i].find("address") != None:
                        address = inventorlist[i].find("address").text[:-3]
                    else:
                        address=''
                    row = [str(self.appnumber),  str(order),  str(korname), str(engname), str(code), str(country), str(address)]
                    wrinventor.writerow(row)
            except:
                pass

    def assignee(self):
        if self.normal == None:
            pass
        else :
            assigneelist = self.note.find("body").find("item").find("applicantInfoArray").findall("applicantInfo")
            for i in range(len(assigneelist)):
                order = i+1
                if assigneelist[i].find("name") != None:
                    korname = assigneelist[i].find("name").text
                else :
                    korname=''
                if assigneelist[i].find("engName")!= None:
                    engname = assigneelist[i].find("engName").text
                else:
                    engname=''
                if assigneelist[i].find("code")!= None:
                    code = assigneelist[i].find("code").text
                else :
                    code =''
                if assigneelist[i].find("country") !=None:
                    country = assigneelist[i].find("country").text
                else:
                    country=''
                if assigneelist[i].find("address") != None:
                    address = assigneelist[i].find("address").text[:-3]
                else:
                    address=''
                row = [str(self.appnumber), str(order), str(korname), str(engname), str(code), str(country) , str(address)]
                wrassignee.writerow(row)

    def ipc(self):
        if self.normal == None:
            pass
        else :
            ipclist = self.note.find("body").find("item").find("ipcInfoArray").findall("ipcInfo")
            for i in range(len(ipclist)):
                if ipclist[i].find("ipcNumber") != None:
                    ipc = ipclist[i].find("ipcNumber").text
                else :
                    ipc = ''
                if ipclist[i].find("ipcDate") != None:
                    ipcdate = ipclist[i].find("ipcDate").text[1:-1]
                else :
                    ipcdate = ''
                row = [str(self.appnumber), str(ipc), str(ipcdate)]
                wripc.writerow(row)


################################################################################################################################
################################################################################################################################
################################################################################################################################

for year in range(1948, 2017):

    ###################################
    ##### Opening Blank csv files #####
    ###################################

    basicinfo = open('D:\\KIPRIS\\Biblio\\csv\\basicinfo_' +str(year) + '.csv', 'w', encoding='utf-8', newline='')
    wrbasicinfo = csv.writer(basicinfo)
    wrbasicinfo.writerow(["appnum", "appdate", "finaldisposal", "registernum", "registerdate", "exmrequst", "nclaim"])
    #출원번호, 출원일자, 등록여부, 등록번호, 등록일자, 심사청구 여부, 청구항 수

    assignee = open('D:\\KIPRIS\\Biblio\\csv\\assignee_' +str(year) + '.csv', 'w', encoding='utf-8', newline='')
    wrassignee = csv.writer(assignee)
    wrassignee.writerow(["appnum", "order", "name", "engname", "code", "country", "address"])

    inventor = open('D:\\KIPRIS\\Biblio\\csv\\inventor_' +str(year) + '.csv', 'w', encoding='utf-8', newline='')
    wrinventor = csv.writer(inventor)
    wrinventor.writerow(["appnum", "order", "name", "engname", "code", "country", "address"])

    ipc = open('D:\\KIPRIS\\Biblio\\csv\\ipc_' +str(year) + '.csv', 'w', encoding='utf-8', newline='')
    wripc = csv.writer(ipc)
    wripc.writerow(["appnum", "ipc", "ipcdate"])

    ############################
    ##### Parsing, Writing #####
    ############################

    xmllist = os.listdir('D:\\KIPRIS\\Biblio\\'+str(year))
    errorlist = []
    for files in xmllist:
        a = writer(files)
        if a.parse_error ==1 or a.successYN == 'N':
            errorlist.append(a.appnumber)
        else:
            pass
        a.basicinfo()
        a.assignee()
        a.inventor()
        a.ipc()
        print(str(a.appnumber))

    ############################
    ##### Saving errorlist #####
    ############################

    with open("D:\\KIPRIS\\Biblio\\csv\\errorlist_"+ str(year)+".csv", "w", newline = '') as errorlist_csv:
        wr = csv.writer(errorlist_csv)
        wr.writerow(errorlist)

    #############################
    ##### Closing csv files #####
    #############################

    basicinfo.close()
    assignee.close()
    inventor.close()
    ipc.close()